<?php
namespace control;
// 模具
class moldClass extends adIndexClass
{
	private const page    = 'mold';
	private const table   = 'mold';
	private const tableMx = 'equipment_detail';
	private const title   = '模具';
	private const state   = ['启用', '停用', '已核减'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'          => [
                        'name'  => "模具类别",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'code'  => [
                        'name'  => '模具编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '模具名称',
                        'width' => 200,
                    ],
                    'model'          => [
                        'name'  => '规格',
                        'width' => 200,
                    ],
                    'mouldLife'          => [
                        'name'  => "模具寿命",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "模具类别"   => select(["name" => "type", 'option' => explode('，', para(self::page . 'Type'))]),
                    "模具编码"   => text(["name" => "code"]),
                    "模具名称"   => text(["name" => "name"]),
                ],
                [
                    "规格" => text(["name" => "model"]),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $url  = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get['cla']}', 'operate', {'act': 'changeState', 'state': '启用'})\">启用</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get['cla']}', 'operate', {'act': 'changeState', 'state': '停用'})\">停用</span>\n";
        }
        if ($this->power(self::page, "import")) {
            $button .=  importTemplateClass::importTemplateButton(self::page) . $this->upButton(array("title" => "导入", "fun" => "importData"));
        }
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 客户列表-查询结果
	 *
	 * @return bool|string
	 */
	public function homeSearch(): string
	{
		if ($this->post('state')) {
			$where = " AND state = '" . $this->post('state') . "'  ";
		} else {
			$where = " AND state <> '已核减' ";
		}
		//查询结果
		$equal = [
			'type' => $this->post('type'),
			'coid' => self::$coid,
		];
		$like  = [
			'code'  => $this->post('code'),
			'name'  => $this->post('name'),
			'model' => $this->post('model'),
		];
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//生成查询语句
		$where                       .= search([
			"="    => $equal,
			"like" => $like,
		]);
		$page                        = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
		$_SESSION[self::page]['sql'] = $page['sql'];

		//获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = [
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
				"edit"   => ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"],
			];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id       = $this->get('id');
		$info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
		$button[]  = [
			"name"  => L('public.save'),
			"type"  => "点击事件",
			"cla"   => $this->get('cla'),
			"fun"   => "subForm('" . self::page . "EditForm', root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
			"post"  => ["id" => $this->get('id')],
			'style' => 'li-btn-blue-bg',
		];
		$button[]  = [
			"name"  => L('public.saveDraft'),
			"type"  => "点击事件",
			"cla"   => $this->get('cla'),
			"fun"   => "saveTemp('" . self::page . "', 'edit', '" . self::page . "EditForm')",
			"post"  => ["id" => $this->get('id')],
			'style' => 'li-btn-green-bg',
		];
		//表单
		$data['html'] = $this->layerEdit([
			"table"  => [
				[
					$this->tableShowButton($button),
				],
				[
					must . '模具名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
				],
				[
					must . '模具类别' => select(['name' => "type", 'class' => 'text', 'value' => $info['type'], 'option' => explode('，', para(self::page . 'Type'))]),
				],
				[
					'厂家' => text(['name' => "factory", 'class' => 'text', 'value' => $info['factory']]),
				],
				[
					must . '规格' => text(['name' => "model", 'class' => 'text', 'value' => $info['model']]),
				],
				[
					'模具寿命' => text(['name' => "mouldLife",'type'=>'number', 'class' => 'text', 'value' => $info['mouldLife']]),
				],
				[
					'备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
				],

			],
			'hidden' => hidden(['name' => 'id', 'value' => $id]),
			'button' => ' ',
		]);

		//返回
		return $this->tab($data);
	}

	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			'name'      => $this->post('name'),
			'type'      => $this->post('type'),
			'model'     => $this->post('model'),
			'factory'   => $this->post('factory'),
			'mouldLife' => $this->post('mouldLife'),
			'text'      => $this->post('text'),
		];
		$annotation = [
			'name'      => '名称',
			'type'      => '类型',
			'model'     => '规格型号',
			'factory'   => '厂家',
			'mouldLife' => '模具寿命',
			'text'      => '备注',
		];
		$rules      = [
			'name'  => 'required',
			'type'  => 'required',
			'model' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} /*/elseif (!empty($info['id']) && $info['state'] == '启用') {
			$json['warn'] = self::title . '不能修改';
		} **/ else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix'  => 'EQ',
                    'default' => '0001',
                    'table'   => self::table,
                    'field'   => 'code',
                    'where'   => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'                 => $id,
					'code'               => $orderNo,
					'mouldRemainingLife' => $field['mouldLife'],
					'state'              => '启用',
					'coid'               => self::$coid,
					'stid'               => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$diff                        = $field['mouldLife'] - $info['mouldLife'];
				$field['mouldRemainingLife'] = $diff + $info['mouldRemainingLife'];
				$json['warn']                = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 详情页
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data = array(
				"id" => $info['id'],
			);

			$button = [];
			if ($this->power(self::page, "edit")) {
				$button[] = [
					"name"  => "编辑",
					"type"  => "顶部页卡",
					"title" => "编辑用户",
					"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
					'style' => 'li-btn-blue-bg',
				];
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
		}
		//生成表单
		$data['html'] = $this->tableShow([
			"button" => $button,
			[
				[
					"模具名称" => $info['name'],
					"模具类别" => $info['type'],
					"规格"   => $info['model'],
				],
				[
					"厂家"   => $info['factory'],
					"模具寿命" => $info['mouldLife'],
				],
				[
					"备注" => $info['text'],
				],
			],
			'状态'     => [
				[
					"模具编号" => $info['code'],
					"制单人"  => self::findStaff($info['stid']),
					"状态"   => $info['state'],
				],
			],
		]);
		//生成页面
		$html = $this->tab($data);
		//返回
		return $html;
	}

	/**
	 * 操作中转
	 *
	 * @return bool|string
	 */
	public function operate()
	{
		$act    = $this->post('act') ?? '';
		$pwd    = $word = false; // 需要密码
		$append = [];
		switch ($act) {
			case 'changeState':
				$act      = 'state';
				$msg      = self::title . '修改状态';
				$title    = self::table . 'Change';
				$function = 'changeState';
				$form     = 'userOperateForm, listForm';
				if ($this->post('state')) {
					$append = [
						0 => hidden(['name' => 'state', 'value' => $this->post('state')]),
					];
				}
				$power = '';
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
				'append'   => $append,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '启用') {
					$warn = "删除失败：模具启用，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					delete(["table" => self::tableMx, "where" => " orderId = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【{$info['id']}】，名称{$info['name']}" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}

	/**
	 * 修改状态
	 *
	 * @return bool|string
	 */
	public function changeState(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		$state = $this->post('state');
		$act   = 'state';
		$json  = [];
		if (!$this->power(self::page, $act)) {
			$json['warn'] = "你没有此权限的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 修改field
			$fieldKey = 'state';
			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if ($info['id']) {
					if ($info['state'] == $state) {
						continue;
					}
					$fieldVlaue = ($info['state'] == '启用') ? '停用' : '启用';
					// 修改状态
					static::update([
						"table" => self::table,
						'field' => [
							$fieldKey => $fieldVlaue,
						],
						"where" => $where,
					]);
					//添加记录
					$text .= "管理员{$this->control['name']}修改了一条" . self::title . "：ID【{$id}】<br>";
					$x++;
				}
			}
			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "修改了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 下载模板
	 */
	public function downloadModel()
	{
		if (!$this->power(self::page, 'import')) {
			$_SESSION['warn'] = '你还没有导入的权限';
		} else {
			$title  = ['*类别', '*模具名称', '厂家', '*规格', '模具寿命', '备注'];
			$data[] = [
				'模具类别一', '模具名称', '厂家名称', '规格', '模具寿命', '备注信息',
				'(样例数据，导入时请删除本条数据)',
			];
			$text   = $this->control['name'] . "下载了" . self::title . "导入模板";
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, '' . self::title . '导入模板.xlsx');
			exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}


	/*数据导入*/
	public function importData()
	{
		if (!$this->power(self::page, 'import')) {
			$_SESSION['warn'] = '你还没有导入的权限';
		} else {
			$data = $this->importHead();
			$x    = 0;
			$text = '';
			foreach ($data as $i => $row) {
				if ($i > 0) {
					$item = formSubArray($row);
					// ['*类别', '*模具名称', '厂家', '*规格', '模具寿命', '备注']
					$field      = [
						'type'      => $item[0],
						'name'      => $item[1],
						'factory'   => $item[2],
						'model'     => $item[3],
						'mouldLife' => $item[4],
						'text'      => $item[5],
					];
					$annotation = [
						'type'      => '类型',
						'name'      => '名称',
						'model'     => '规格型号',
						'factory'   => '厂家',
						'mouldLife' => '模具寿命',
						'text'      => '备注',
					];
					$rules      = [
						'type'  => 'required',
						'name'  => 'required',
						'model' => 'required',
					];
					// 校验是否符合规则
					$vt     = new \verify();
					$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
					if ($result === false) {
						$text .= "\n第【{$i}】行，" . $vt->getErrs()[0];
					} elseif (!in_array($field['type'], explode('，', para(self::page . 'Type')))) {
						$text .= "\n第【{$i}】行，模具【{$field['name']}】，分类【{$field['type']}】 不在模具分类中";
					} else {
						$where = generateWhere([
							'coid'  => self::$coid,
							'type'  => $field['type'],
							'code'  => $field['code'],
							'name'  => $field['name'],
							'model' => $field['model'],
						]);
						$info  = query(self::table, $where);
						// 新增
						if (static::isNull($info['id'])) {
							$orderNo = codeTemplateClass::generateCode(self::page,[
                                'prefix'  => 'EQ',
                                'default' => '0001',
                                'table'   => self::table,
                                'field'   => 'code',
                                'where'   => " AND coid = '" . self::$coid . "' ",
                            ],$field);
							$field   = array_merge($field, [
								'id'                 => self::getNo(),
								'code'               => $orderNo,
								'state'              => '启用',
								'mouldRemainingLife' => $field['mouldLife'],
								'coid'               => self::$coid,
								'stid'               => $this->control['stid'],
							]);
							$warn    = static::insert([
								"table" => self::table,
								"field" => $field,
							]);
						} else {
							$diff                        = $field['mouldLife'] - $info['mouldLife'];
							$field['mouldRemainingLife'] = $diff + $info['mouldRemainingLife'];
							$warn                        = static::update([
								"table" => self::table,
								"field" => $field,
								'where' => $where,
							]);
						}
						if (in_array($warn, ["新增成功", "更新成功"])) {
							$x++;
							$text .= "模具【$item[1]-$item[2]】导入成功<br>";
						} else {
							$text .= "模具【$item[1]-$item[2]】导入失败：编辑失败<br>";
						}
					}
				}
			}
			$text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$warn             = "成功导入" . $x . "条数据，详情请查看日志！";
			$_SESSION['warn'] = $warn;
		}
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}

	/**
	 * 导出
	 */
	public function exportData()
	{
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = '你还没有导出的权限';
		} else {
			$tr              = [];
			$sql             = $_SESSION[self::page]['sql'];
			$result['array'] = sqlFind($sql);
			$title           = ['模具类别', '模具编码', '模具名称', '规格', '模具寿命', '状态'];
			if (is_array($result['array'])) {
				foreach ($result['array'] as $array) {
					//本行
					$tr[] = [$array['type'], $array['code'], $array['name'], $array['model'], $array['mouldLife'], $array['state']];
				}
			}
			$text = $this->control['name'] . "导出了模具信息";
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $tr, "模具信息.xlsx");
		}
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}

    /**
     * 组装名称
     * @param $id
     * @param string $interval
     * @return string
     */
	public static function getName($id, $interval = '-'): string
    {
	    $info = query(self::table,"id = '$id'");
        $name = $info['code']?$info['code'].$interval:'';
	    $name .= $info['name']?$info['name'].$interval:'';
	    $name.=$info['model']?$info['model'].$interval:'';
        return rtrim($name, $interval);
    }
}
